<?php
namespace app\api\controller;
use think\Db;
use think\request;
use think\Controller;
use app\common\model\Prt;
use app\common\model\Csv;
class Sy extends Controller
{
	protected function _initialize() {
		header('Access-Control-Allow-Origin:*');
	}
	function get_levels(){
		 $where['store_id']=input("store_id");
	 	 $houses=db("dinner")->where($where)->select();
		 return json(['list'=>$houses]);
	}
	function get_dinners(){
		 $where['store_id']=input("store_id");
	 	 $houses=db("dinner")->where($where)->select();
		 return json(['list'=>$houses]);
	}
	function get_loginfo(){
		$paylog=db('paylog')->where('id',input("log_id"))->find();
		$goods=array();
//		$field="goods_name";
//		if($paylog['goods_id']){
//			$good=db('agent_goods')->where("id",$paylog['goods_id'])->find();
//			$good['num']=$paylog['goods_num'];
//			$good['price']=$paylog['origin_price'];
//			$goods[]=$good;
//		}else if($paylog['order_id']){
//			$goods=db('agent_syorder_items')->alias('a')->
//			join("agent_goods b","a.goods_id=b.id","left")->where("order_id",$paylog['order_id'])->field("b.goods_name,a.num,a.price,a.unit")->select();
//		}
		return json(["log"=>$paylog,"goods"=>$goods]);
	}
	public function jizhang($house_id,$house_id){
		
		$res=db("dinner")->where("id",$house_id)->update(['status'=>1]);
		$res=db("reserve_ct")->where("room_id",$house_id)->update(['status'=>2,'state'=>4]);
		return (['code'=>200,'msg'=>'操作成功']);
	}
	public function update_house($house_id,$status){
		$res=db("dinner")->where("id",$house_id)->update(['status'=>$status]);
		if($status==1){
			db("reserve_ct")->where("room_id",$house_id)->update(['status'=>2]);
		}
		if($res){
			return (['code'=>200,'msg'=>'操作成功']);
		}
			return (['code'=>400,'msg'=>'操作失败']);
	}
		//修改房台订单
	public function cg_order(){
		Db::startTrans();
		$order_id=input("order_id");
		$type=input('type');//1增加2减少
		$item_id=input("item_id");
		$price=input('price');
		if($type==1){
			$up['origin_price']=["inc",$price];
			$item_up['num']=['inc',1];
		}else{
			$up['origin_price']=["dec",$price];
			$item_up['num']=['dec',1];
		}
		
		$res=db("reserve_ct")->where('id',$order_id)->update($up);
		$result=true;
		if(!$res){
			$result=false;
		}
		$res=db('reserve_item')->where('id',$item_id)->update($item_up);
		if(!$res){
			$result=false;
		}
		if(!$result){
			Db::rollback();
			return json(["code"=>400,'msg'=>'修改失败']);
		}else{
			Db::commit();
			return json(["code"=>200,'msg'=>'修改成功']);
		}
	}
	//點餐下單
	public function add_horder($store_id,$house_id,$emp_id){
		$status=input("status");
		$where['room_id']=$house_id;
		$where['status']=1;
		$goods=input('post.')['data'];
		$items=array();
		$add_time=now_time();
		$where['store_id']=$store_id;
		$where['state']=['neq',4];
		
		
		$order=db("reserve_ct")->where($where)->find();
		$total_price=0;
		foreach($goods as $i){
			$total_price+=$i['price'];
		}
		
		if($order){
			$res=db("reserve_ct")->where("id",$order['id'])->setInc("origin_price",$total_price);
		}else{
			$data['store_id']=$store_id;
			$data['room_id']=$house_id;
			$data['state']=1;
			$data['origin_price']=$total_price;
			$data['memo']=input("memo");
			$data['nums']=input("people_nums");
			$r_id=db("reserve_ct")->insertGetId($data);
			$order=db("reserve_ct")->find($r_id);
			db("dinner")->where("id",$house_id)->update(['status'=>2]);
		}
		foreach($goods as $i){
			$items[]=array('type'=>$i['type_id'],'add_time'=>now_time(),"r_id"=>$order['id'],"caipin_id"=>$i['id'],"price"=>$i['price'],"num"=>$i['num'],"store_id"=>$store_id,"name"=>$i['name']);
		}
		$res2=db('reserve_item')->insertAll($items);
		if($res2){
			
			$prt=new Prt();	
			//$prt->print_items($res);
			$items=db("reserve_item")->where("r_id",$order['id'])->select();
			return json(['code'=>200,'msg'=>"下单成功 ","order_id"=>$order['id'],"items"=>$items,'total_price'=>$total_price]);
		}else{
			return json(['code'=>400,'msg'=>"下单失败 "]);
		}
	}
	//校验商品库存
	function check_stock(){
		$good=db("caipin")->where("id",input('goods_id'))->find();
		if($good){
			if($good['store']>input("nums")){
				return json(['code'=>200]);
			}else{
				return json(['code'=>400,'msg'=>'商品库存不足！还剩下'.$good['stock'].'份了']);
			}
		}else{
			return json(['code'=>404,'商品不存在']);
		}
	}
	//商品收银
	public function goods_sk(){
		 $where['store_id']=input("store_id");
		 $where['store']=['>',0];
		 $where['status']=1; 
	 	 $goods=db("caipin")->where($where)->select();
		 //$type=$this->getTypes($store_id);
		 $type=db('caipin_type')->select();
		 $type1=array();
		 $res=array();
		 foreach($type as $k=>$v){
				$type1[$v['id']]=$v;
		 }
		 foreach($goods as $k=>$v){
		 	$res[$v['type_id']][]=$v;
		 }
		 $data['type']=$type;
		 return json(['res'=>$res,'type'=>$type1]);
	 }
	
		
	/**
	 * 会员卡收款
	 * */
	public function shouk(){
		$user_info = db('user')->alias('a')->join('userlevel b','a.level_id=b.id','LEFT')->where('a.id',$_POST['user_id'])->field('a.balance,a.level_id,a.id,a.mobile,a.user_name,b.name as level_name,b.discount')->find();
		//折扣
		$discount=0;
		if($user_info['level_id']>0){
			$discount=db("storediscount")->where(["store_name_id"=>$_POST['store_id'],'userlevel'=>$user_info['level_id']])->value('discount');
		}
		$log=db("reserve_ct")->where("id",$_POST['order_id'])->find();
		$origin_price=$log['origin_price'];
		$balance=$log['origin_price'];
		if($discount>0){
			$zk = $discount/100;//折扣
			$balance = $origin_price*$zk;//参与折扣金额
		}	
		if($user_info['balance']<$balance){
			return json(['code'=>400,"msg"=>'会员卡余额不足']);
		}	
		//订单信息
		Db::startTrans();
		$res=[];
		$order_sn = order_create_no();
		$res[] =dinner_log($log['store_id'],$_POST['user_id'],$origin_price,10,$order_sn,5,'点餐会员卡付款',$balance,$_POST['emp_id'],$log['room_id']);
		$res[]=db('user')->where('id',$_POST['user_id'])->setDec('balance',$balance);  //更新用户表
		$res[]=card_xf_log($res,$_POST['user_id'],0,$balance,$user_info['level_id'],0,0,now_time(),2,0,'会员卡支付');//会员卡消费
		if (in_array(false, $res)){
		    Db::rollback();
			return json(['code'=>400,"msg"=>'支付失败']);
		}else {
		    Db::commit();
			$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
			return json(['code'=>200,"msg"=>'支付成功','order_id'=>$order_id]);
		}
	}
	/**
	 * 扫一扫收款
	 * */
	public function sys_pay(){
		$pay_type=get_bartype($_POST["mem_card"]);//判断是微信还是支付宝打开
		$order_sn = order_create_no();
		//$log=db("")
		Db::startTrans();
		$log=db("reserve_ct")->where("id",$_POST['order_id'])->find();
		$res[] =dinner_log($log['store_id'],0,$log['origin_price'],10,$order_sn,$pay_type,'点餐扫码付款',$log['origin_price'],$_POST['emp_id'],$log['room_id']);
		$result=bar_pay($_POST["mem_card"],'H480','ea4f13f136c95a617b1acfbda7af6eb1','45a7a757b685f5c890b815839e58ca18',$log['origin_price'],1,$order_sn,'');
		if($result==2 && $res==true){
			Db::commit();
			db('reserve_ct')->where("id",$log['id'])->update(['status'=>2,'state'=>4]);
			db('dinner')->where("id",$log['room_id'])->update(['status'=>0]);
			$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
			return json(['code'=>200,"msg"=>'收款成功','order_id'=>$order_id]);
		}else{
			Db::rollback();
			return json(["code"=>400,'msg'=>'系统繁忙请稍后再试!']);
		}
	}
		/**
	 * 获取房台信息
	 */
	public function get_houseinfo(){
		$house=db("dinner")->find(input("house_id"));
		
		$house['add_time']=substr($house['add_time'], 11,18);
		$where['room_id']=input("house_id");
		
		$where['store_id']=$house['store_id'];
		$where['status']=1;
		$order=db("reserve_ct")->where($where)->find();
		if($order){
			$list=db("reserve_item")->where("r_id",$order['id'])->select();
			$order['item']=$list;
			return json(['code'=>200,'data'=>$order,'house'=>$house]);
		}
		return json(['code'=>406,'msg'=>'未点单','house'=>$house]);
	}
	//根据类型获取房台
	public function get_housesbt(){
		$where['store_id']=input("store_id");
		$where['state']=1;
		if(input("type_id")){
			$where['area_id']=input("type_id");
		}
	 	$houses=db("dinner")->where($where)->select();
		return json(['houses'=>$houses]);
	}
	//房台收银
	public function get_houses(){
		 $where['store_id']=input("store_id");
	 	 $houses=db("dinner")->where($where)->select();
		 //$type=$this->getTypes($store_id);
		 $type=db('area')->where($where)->select();
		 $type1=array();
		 $res=array();
		 foreach($type as $k=>$v){
				$type1[$v['id']]=$v;
		 }
		 foreach($houses as $k=>$v){
		 	$res[$v['area_id']][]=$v;
		 }
		 $data['type']=$type;
		 return json(['res'=>$res,'type'=>$type1]);
	 }
	//收银报表
	public function get_reports(){
		$where['a.add_time']=array('egt',$_POST['login_time']);//上班时间数据统计
		$where['a.staff_id']=input('id');
		$where['a.state']=2;
		if(input("pay_type")){
			$where['a.pay_type']=input("pay_type");
		}
		if(input("type")){
			$where['a.type']=input("type");
		}
		if(input("sn")){
			$where['a.order_sn']=["like","%".input("sn")."%"];
		}
		if(input("start_time")&&input("end_time")){
			$where['a.add_time']=['between',[input('start_time'),input('end_time')]];
		}else{
			if(input("start_time")){
				$where['a.add_time']=[">=",input('start_time')];
			}
			if(input("end_time")){
				$where['a.add_time']=["<=",input('end_time')];
			}
		}
		
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		$pg=$page-1;
		$begin=$pg*4;
		$count=db('paylog')->alias('a')->where($where)->count();
		$list=db('paylog')->alias('a')->field('a.*,b.room_num,c.room_name,d.name as emp_name')
		->join('reserve b','a.id=b.order_id','LEFT')->join('room_sort c','a.room_id=c.id','LEFT')->join('emp d','a.staff_id=d.id','LEFT')
		->where($where)->limit($begin,4)->order("a.add_time desc")->select();
		return json(["list"=>$list,"count"=>$count]);
	}
	/**
	 * 退款
	 * */
	function refund(){
		if($_POST){
			//todo-- 判断操作密码是否正确
			$oppass = db('emp')->where('id',$_POST['staff_id'])->value('oppass');
			if(md5_salt($_POST['pwd'])!==$oppass){
				return json(["code"=>400,'msg'=>'操作密码不正确!']);
			}
			$update['tk_msg'] = $_POST['msg'];
			$update['tk_money'] = $_POST['tk_money'];
			$update['tk_time'] = now_time();
			$update['is_tk'] = 1;//是否退款
			
			$paylog = db('paylog')->where('id',$_POST['order_id'])->find();
			if($paylog['is_tk']==1){
				return false;
			}
			if($_POST['tk_money']>$paylog['balance']){
				return json(["code"=>400,'msg'=>'退款金额不可大于实际支付金额!']);
			}
			//订单信息
			Db::startTrans();
			$res=[];
			if($paylog['pay_type']==5){//会员卡
				$res[]=db('user')->where('id',$paylog['user_id'])->setInc('balance',$paylog['balance']);  //更新用户表
			}
			
			//微信支付宝支付退款返回原账户
			if($paylog['pay_type']==2 || $paylog['pay_type']==3){
				$order_refund= order_refund($paylog['order_sn'],$_POST['tk_money'],"H480","ea4f13f136c95a617b1acfbda7af6eb1","45a7a757b685f5c890b815839e58ca18");
				if($order_refund==1)$res[]=true;
			}
			$res[]=db('paylog')->where('id',$paylog['id'])->update($update);//更新支付表
			$res[]=card_xf_log($paylog['order_sn'],$paylog['user_id'],0,$_POST['tk_money'],$paylog['level_id'],$paylog['pay_type'],0,now_time(),8,0,'收银台退款');//退款
			$payinfo = db('paylog')->where(['id'=>$paylog['id']])->find();
			$payinfo['msg']='退款';
			$payinfo['type'] = 4;//退款
			$payinfo['order_id'] = $payinfo['id'];
			$order_sn = order_create_no();
			$payinfo['order_sn'] =  $order_sn;
			$payinfo['add_time'] =  now_time();
			unset($payinfo['id']);
			$res[] = db('paylog')->insert($payinfo);
			if (in_array(false, $res)){
			    Db::rollback();
				return json(["code"=>400,'msg'=>'退款失败!']);
			}else {
			    Db::commit();
				$order_id = db('paylog')->where('order_sn',$order_sn)->value('id');
				return json(["code"=>200,'msg'=>'退款成功!','order_id'=>$order_id]);
			}
		}
	}

	/**
	 * 打印
	 * */
	function prt(){
		$store_id = db('paylog')->where('id',input('order_id'))->value('store_id');
		$is_prt = db('printer')->where("store_id",$store_id)->find();
		if($is_prt){
			$prt=new Prt();	
			$res=$prt->print_order(input("order_id"));	
			return json(['code'=>200,'msg'=>'打印成功']);
		}else{
			return json(['code'=>400,'msg'=>'打印失败，未配置打印机']);
		}
		
	}
	//预定
	function reserve_list(){
		$store_id = input('store_id');
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		if(input('mobile')){
			$where['mobile'] = input('mobile');
		}
		$where['type']=2;
		if(input("start_time") && input("end_time")){
			$where['a.add_time']=["between time",[input("start_time"), input("end_time")]];
		}else{
			if(input("start_time")){
				$where['a.start_time']=[">=",input('start_time')];
			}
			if(input("end_time")){
				$where['a.start_time']=["<=",input('end_time')];
			}
		}
		
		$where['store_id'] = $store_id;
		$count = db('reserve_ct')->alias('a')->join('user b','a.user_id=b.id','LEFT')->where($where)->order('a.id desc')->count();
		$reserve_list = db('reserve_ct')->alias('a')
						->field('a.*,b.mobile,b.user_name')
						->join('user b','a.user_id=b.id','LEFT')
						->where($where)
						->order('a.id desc')
						->page($page,7)
						->select();
		return json(["reserve_list"=>$reserve_list,"count"=>$count]);
	}
	
	//交易信息
	function deal_order(){
		$store_id = input('store_id');
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		if(input('order_sn')){
			$where['order_sn'] = input('order_sn');
		}
		
		if(input("start_time") && input("end_time")){
			$where['a.add_time']=["between time",[input("start_time"), input("end_time")]];
		}else{
			if(input("start_time")){
				$where['a.add_time']=[">=",input('start_time')];
			}
			if(input("end_time")){
				$where['a.add_time']=["<=",input('end_time')];
			}
		}
		
		$where['store_id'] = $store_id;
		$count = db('paylog')->alias('a')->field('a.*,b.name')->join('emp b','a.staff_id=b.id','LEFT')->where($where)->order('a.id desc')->count();
		$paylog_list = db('paylog')->alias('a')
						->field('a.*,b.name')
						->join('emp b','a.staff_id=b.id','LEFT')
						->where($where)
						->order('a.id desc')
						->page($page,7)
						->select();
		return json(["paylog_list"=>$paylog_list,"count"=>$count]);
		
	}
	
	function get_member_list(){
		$mobile = input('mobile');
		if(input("page")){
			$page=input("page");
		}else{
			$page=1;
		}
		if(!empty($mobile)){
			$where['a.mobile'] = $mobile;
		}
		
		if(input("start_time") && input("end_time")){
			$where['a.add_time']=["between time",[input("start_time"), input("end_time")]];
		}else{
			if(input("start_time")){
				$where['a.add_time']=[">=",input('start_time')];
			}
			if(input("end_time")){
				$where['a.add_time']=["<=",input('end_time')];
			}
		}
		
		$recharge_sql = db('consume')->field('user_id,sum(balance) as recharge_money')->where('type',1)->group('user_id')->buildsql();
		$consume_sql = db('consume')->field('user_id,sum(balance) as consume_money')->where('type',2)->group('user_id')->buildsql();
		
		$where['a.id'] = ['>',0];
		$count = db('user')->alias('a')->field('a.*,b.name as level_name')->join('userlevel b','a.level_id=b.id','LEFT')->where($where)->order('a.id desc')->count();
		$user_list = db('user')->alias('a')
						->field('a.*,b.name as level_name,c.recharge_money,d.consume_money')
						->join('userlevel b','a.level_id=b.id','LEFT')
						->join($recharge_sql.' c','a.id=c.user_id','LEFT')
						->join($consume_sql.' d','a.id=d.user_id','LEFT')
						->where($where)
						->order('a.id desc')
						->page($page,7)
						->select();
		return json(["user_list"=>$user_list,"count"=>$count]);
	}
	
	//预定开台
	function reserve_opent(){
		$result = true;
		Db::startTrans();
		
		$type = input('type');
		
		try{
			if($type ==1){
				$rest1 = db('dinner')->where('id',input('dinner_id'))->update(['status'=>2]);
				if(!$rest1) $result=false;
				
				$rest2 = db('reserve_ct')->where('id',input('reserve_id'))->update(['room_id'=>input('dinner_id'),'state'=>3]);
				if(!$rest2) $result=false;
				$msg = '开台';
			}else{
				$rest1 = db('dinner')->where('id',input('dinner_id'))->update(['status'=>1]);
				if(!$rest1) $result=false;
				
				$rest2 = db('reserve_ct')->where('id',input('reserve_id'))->update(['state'=>4]);
				if(!$rest2) $result=false;
				$msg = '关台';
			}
			
			if($result){
				return json(['code'=>200,'msg'=>$msg.'成功']);
				Db::commit(); 
			}else{
				return json(['code'=>403,'msg'=>$msg.'失败']);
				Db::rollback();
			}
			
			
		}catch(Exception $e){
			Db::rollback();
		 	echo 'Message: ' .$e->getMessage();
		 	return json(['code'=>405,'msg'=>'数据异常']);
		}
		
	}
	
	
}
